/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on 23.05.2011, 19:57:25
 */
package playboxclient;

import java.io.StringReader;
import java.util.ArrayList;
import javax.swing.JOptionPane;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jdesktop.application.Action;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author martin
 */
public class Login extends javax.swing.JDialog {

    /** Creates new form Login */
    public Login(java.awt.Frame parent, PlayBoxClientView papa) {
        super(parent);
        father = papa;
        initComponents();
        //getRootPane().setDefaultButton(closeButton);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtf_username = new javax.swing.JTextField();
        jpwf_password = new javax.swing.JPasswordField();
        jbut_cancel = new javax.swing.JButton();
        jbut_ok = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(null);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(playboxclient.PlayBoxClientApp.class).getContext().getResourceMap(Login.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jtf_username.setText(resourceMap.getString("jtf_username.text")); // NOI18N
        jtf_username.setName("jtf_username"); // NOI18N
        jtf_username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtf_usernameActionPerformed(evt);
            }
        });

        jpwf_password.setText(resourceMap.getString("jpwf_password.text")); // NOI18N
        jpwf_password.setName("jpwf_password"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(playboxclient.PlayBoxClientApp.class).getContext().getActionMap(Login.class, this);
        jbut_cancel.setAction(actionMap.get("doCancel")); // NOI18N
        jbut_cancel.setText(resourceMap.getString("jbut_cancel.text")); // NOI18N
        jbut_cancel.setName("jbut_cancel"); // NOI18N
        jbut_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbut_cancelActionPerformed(evt);
            }
        });

        jbut_ok.setAction(actionMap.get("doLogin")); // NOI18N
        jbut_ok.setText(resourceMap.getString("jbut_ok.text")); // NOI18N
        jbut_ok.setName("jbut_ok"); // NOI18N
        jbut_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbut_okActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jpwf_password)
                            .addComponent(jtf_username, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(100, 100, 100)
                        .addComponent(jbut_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbut_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(119, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jtf_username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jpwf_password, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbut_cancel)
                    .addComponent(jbut_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(49, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtf_usernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtf_usernameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtf_usernameActionPerformed

    private void jbut_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbut_cancelActionPerformed
        // TODO add your handling code here:
    }

    @Action
    public void doCancel() {
        this.setVisible(false);
    }//GEN-LAST:event_jbut_cancelActionPerformed

    /**
     * Führe Login-Versuch durch. Bei Fehler wird ein MessageBox angezeigt und
     * ist wieder für eine Eingabe bereit.
     * @param evt 
     */
    private void jbut_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbut_okActionPerformed
        // TODO add your handling code here:

        // Create  Basic-AuthLogin-HTTP-Request and Get GAME-List for Acknowledge!
        // 

        ArrayList<String> listofgamesavailable = new ArrayList<String>();

        System.out.println("Pressed");


        playboxws.PlayBoxWS_Service service = new playboxws.PlayBoxWS_Service();
        playboxws.PlayBoxWS port = service.getPlayBoxWSPort();

        PasswordService ps = PasswordService.getInstance();

        //String str = port.getGameList(this.jtf_username.getText(), new String(this.jpwf_password.getPassword()));

        // falls die passwörter gehasht übertragen werden sollen, folgende zeile statt vorheriger verwenden
        String str = port.getGameList(this.jtf_username.getText(), ps.getHash(new String(this.jpwf_password.getPassword()), this.jtf_username.getText()));

        System.out.println(str);
        try {
            StringReader inStream = new StringReader(str);
            InputSource inSource = new InputSource(inStream);

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(inSource);
            doc.getDocumentElement().normalize();
            System.out.println(doc.getDocumentElement().getTextContent());

            NodeList nodes = doc.getElementsByTagName("name");

            if (nodes.getLength() > 0) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    listofgamesavailable.add(element.getTextContent());
                    System.out.println(element.getTextContent());
                }
                // Erfolgreich: setze Client-Flag.
                father.setLoggedin(listofgamesavailable, this.jtf_username.getText(), new String(this.jpwf_password.getPassword()));
                //wenn liste leer ist
                //dh user hat sich nicht richtig angemeldet
            } else {
                JOptionPane.showMessageDialog(this, "Username oder PW sind nicht korrekt", "Login Fehler", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            System.out.println("Fehler:" + e.getMessage());
        }
        

        if (father.getLoggedinStatus() == true) {
            this.dispose();
        }



    }//GEN-LAST:event_jbut_okActionPerformed
    /**
     * @param args the command line arguments
     */
    /*public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    
    public void run() {
    Login dialog = new Login(new javax.swing.JFrame(), true);
    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
    
    public void windowClosing(java.awt.event.WindowEvent e) {
    System.exit(0);
    }
    });
    dialog.setVisible(true);
    }
    });
    }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton jbut_cancel;
    private javax.swing.JButton jbut_ok;
    private javax.swing.JPasswordField jpwf_password;
    private javax.swing.JTextField jtf_username;
    // End of variables declaration//GEN-END:variables
    private PlayBoxClientView father;
}
